import React, { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Input,
  InputNumber,
  Switch,
  Button,
  Space,
  Typography,
  Alert,
  Spin,
  message,
  Divider,
  Tooltip,
} from 'antd'
import {
  DatabaseOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
} from '@ant-design/icons'
import type { Connection, CreateConnectionData, UpdateConnectionData, ConnectionTestResult } from '@/types/connection'
import { testConnection } from '@/services/connectionAPI'

const { Text } = Typography
const { TextArea } = Input

interface ConnectionFormProps {
  visible: boolean
  connection?: Connection
  onCancel: () => void
  onSubmit: (data: CreateConnectionData | UpdateConnectionData) => Promise<void>
  loading?: boolean
}

const ConnectionForm: React.FC<ConnectionFormProps> = ({
  visible,
  connection,
  onCancel,
  onSubmit,
  loading = false,
}) => {
  const [form] = Form.useForm()
  const [testLoading, setTestLoading] = useState(false)
  const [testResult, setTestResult] = useState<ConnectionTestResult | null>(null)
  const [showPassword, setShowPassword] = useState(false)

  const isEdit = !!connection

  // 重置表单
  useEffect(() => {
    if (visible) {
      if (connection) {
        form.setFieldsValue({
          name: connection.name,
          host: connection.host,
          port: connection.port,
          username: connection.username,
          database_name: connection.database_name,
          description: connection.description,
          is_active: connection.is_active,
        })
      } else {
        form.resetFields()
        form.setFieldsValue({
          port: 9030, // Doris默认端口
          is_active: true,
        })
      }
      setTestResult(null)
    }
  }, [visible, connection, form])

  // 测试连接
  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields(['host', 'port', 'username', 'password'])
      setTestLoading(true)
      setTestResult(null)

      // 如果是编辑模式且有连接ID，使用现有连接测试
      if (isEdit && connection) {
        const result = await testConnection(connection.id)
        if (result.success) {
          setTestResult(result.data)
        } else {
          setTestResult({
            success: false,
            message: result.message || '连接测试失败',
          })
        }
      } else {
        // 新建连接时，需要临时创建连接进行测试
        // 这里模拟测试结果
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 模拟测试结果
        const mockResult: ConnectionTestResult = {
          success: Math.random() > 0.3, // 70%成功率
          message: Math.random() > 0.3 ? '连接成功' : '连接失败：无法连接到数据库服务器',
          databases: Math.random() > 0.3 ? ['test_db', 'analytics', 'warehouse'] : undefined,
          response_time: Math.floor(Math.random() * 500) + 100,
        }
        
        setTestResult(mockResult)
      }
    } catch (error) {
      console.error('Connection test failed:', error)
      setTestResult({
        success: false,
        message: '连接测试失败，请检查参数配置',
      })
    } finally {
      setTestLoading(false)
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      await onSubmit(values)
      message.success(isEdit ? '连接更新成功' : '连接创建成功')
    } catch (error) {
      console.error('Form submission failed:', error)
    }
  }

  // 渲染测试结果
  const renderTestResult = () => {
    if (!testResult) return null

    return (
      <Alert
        type={testResult.success ? 'success' : 'error'}
        message={
          <Space>
            {testResult.success ? (
              <CheckCircleOutlined style={{ color: '#52c41a' }} />
            ) : (
              <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
            )}
            <span>{testResult.message}</span>
            {testResult.response_time && (
              <Text type="secondary">({testResult.response_time}ms)</Text>
            )}
          </Space>
        }
        description={
          testResult.success && testResult.databases && (
            <div>
              <Text strong>可用数据库：</Text>
              <Text code>{testResult.databases.join(', ')}</Text>
            </div>
          )
        }
        style={{ marginTop: 16 }}
      />
    )
  }

  return (
    <Modal
      title={
        <Space>
          <DatabaseOutlined />
          <span>{isEdit ? '编辑连接' : '新建连接'}</span>
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="test"
          icon={testLoading ? <LoadingOutlined /> : undefined}
          onClick={handleTestConnection}
          loading={testLoading}
        >
          测试连接
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={handleSubmit}
          loading={loading}
        >
          {isEdit ? '更新' : '创建'}
        </Button>,
      ]}
      width={600}
      maskClosable={false}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          port: 9030,
          is_active: true,
        }}
      >
        <Form.Item
          name="name"
          label="连接名称"
          rules={[
            { required: true, message: '请输入连接名称' },
            { max: 100, message: '连接名称不能超过100个字符' },
          ]}
        >
          <Input placeholder="请输入连接名称" />
        </Form.Item>

        <Form.Item
          name="host"
          label="主机地址"
          rules={[
            { required: true, message: '请输入主机地址' },
            { max: 255, message: '主机地址不能超过255个字符' },
          ]}
        >
          <Input placeholder="例如：192.168.1.100 或 doris.example.com" />
        </Form.Item>

        <Form.Item
          name="port"
          label="端口"
          rules={[
            { required: true, message: '请输入端口号' },
            { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间' },
          ]}
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="9030"
            min={1}
            max={65535}
          />
        </Form.Item>

        <Form.Item
          name="username"
          label="用户名"
          rules={[
            { required: true, message: '请输入用户名' },
            { max: 100, message: '用户名不能超过100个字符' },
          ]}
        >
          <Input placeholder="请输入数据库用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: !isEdit, message: '请输入密码' },
          ]}
        >
          <Input.Password
            placeholder={isEdit ? '留空表示不修改密码' : '请输入数据库密码'}
            iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
          />
        </Form.Item>

        <Form.Item
          name="database_name"
          label="默认数据库"
          extra="可选，指定默认连接的数据库"
        >
          <Input placeholder="请输入默认数据库名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
          extra="可选，添加连接的描述信息"
        >
          <TextArea
            rows={3}
            placeholder="请输入连接描述"
            maxLength={500}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="is_active"
          label="启用连接"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        {renderTestResult()}
      </Form>

      <Divider />

      <Alert
        message="连接安全提示"
        description={
          <ul style={{ margin: 0, paddingLeft: 20 }}>
            <li>密码将被加密存储，确保数据安全</li>
            <li>建议使用专用的数据库账户，避免使用管理员账户</li>
            <li>定期更新密码，提高安全性</li>
            <li>测试连接成功后再保存配置</li>
          </ul>
        }
        type="info"
        showIcon
      />
    </Modal>
  )
}

export default ConnectionForm